//
//  LoginManager.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-1.
//
//

#import "CubeModuleManager.h"
#import "DataCenter.h"
#import "Modules.h"
#import "IsolatedStorageFile.h"
#import "CubeModuleWorkTask.h"
#import "JSONParser.h"
#import "BSLCubeConstant.h"

@interface CubeModuleManager()
-(void)saveLocalModuleList;
@end

@implementation CubeModuleManager

-(id)init{
    self=[super init];
    
    if(self){
        asyncs=[[NSMutableArray alloc] initWithCapacity:2];
    }
    
    return self;
}

- (void)dealloc{
}


-(void)syncModuleList:(NSArray*)remoteServiceList{
        
    //本地的service模块全部替换成最新模块
    if([remoteServiceList count]>0)
        [DataCenter defaultCenter].serviceModules = remoteServiceList;
    
    NSMutableArray* installModuleList=[DataCenter defaultCenter].installMoudules;
    
    //同步已安装列表
    //临时遍历用列表，为了线程安全
    NSArray* temModuleList =[NSArray arrayWithArray:installModuleList];
    remoteServiceList=[DataCenter defaultCenter].serviceModules;
    
    for(CubeModel* iModule in temModuleList){
        
        CubeModel* serviceModel=nil;
        for(CubeModel* _serviceModel in remoteServiceList){
            if([_serviceModel.identifier isEqualToString:iModule.identifier]){
                serviceModel=_serviceModel;
                break;
            }
        }
        
        if (serviceModel==nil){
            //服务器更改了关联关系，已安装模块列表得删除该模块
            [installModuleList removeObject:iModule];
        }
        else{
            
            //版本相同，则属性覆盖
            if (iModule.build == serviceModel.build){
                iModule.autoDownload = serviceModel.autoDownload;
                iModule.name = serviceModel.name;
                iModule.releaseNote = serviceModel.releaseNote;
            }
            else if (iModule.build < serviceModel.build){
                //版本不同，应用设置为可更新
                iModule.moduleType = CubeMoudleStatusCanUpdate;
            }
        }
    }
    
    //保存至本地文件系统
    [self saveLocalModuleList];
    
}
-(void)loadLocalModuleList:(BOOL)isInstallMoudules{
    
    NSArray* list=[NSKeyedUnarchiver unarchiveObjectWithFile:[IsolatedStorageFile moudlelistDirectory]];
    
    NSMutableArray* installList=[[NSMutableArray alloc] initWithCapacity:2];
    
    //如果某些模块未下载完成，则更新的保留，未下载的移除
    for (int i = 0; i < [list count]; i++){
            CubeModel* module =[list objectAtIndex:i];
        if (module.moduleType == CubeMoudleStatusFinish || module.moduleType==CubeMoudleStatusCanUpdate || module.moduleType==CubeMoudleStatusUpdating){
            [installList addObject:module];
        }
    }
    if (isInstallMoudules) {
        [DataCenter defaultCenter].installMoudules=installList;
    }
    else{
        [DataCenter defaultCenter].serviceModules=installList;
    }

    
    if([DataCenter defaultCenter].installMoudules==nil)
        [DataCenter defaultCenter].installMoudules=[[NSMutableArray alloc] init];

}
-(void)saveLocalModuleList{
    [NSKeyedArchiver archiveRootObject:[DataCenter defaultCenter].installMoudules toFile:[IsolatedStorageFile moudlelistDirectory]];
}


-(CubeModel*)findDownloadingCubeModule:(NSString*)identifier{
    for(CubeModuleWorkTask* task in asyncs){
        if ([task.cubeModel.identifier isEqualToString:identifier]){
                return task.cubeModel;
        }
    }
    return nil;
}


-(void)cancel{
    for(CubeModuleWorkTask* async in asyncs){
        async.callback=nil;
        [async cancel];
    }
    [asyncs removeAllObjects];
    
}

-(NSUInteger)downloadCount{
    return [asyncs count];
}

-(void)installModule:(NSString*)identifier{
    NSMutableArray* installMoudules = [[DataCenter defaultCenter] installMoudules];
    for (CubeModel* model in installMoudules){
        if ([model.identifier isEqualToString:identifier]){
            return;
        }
    }
    
    for(CubeModuleWorkTask* async in asyncs){
        if([async.cubeModel.identifier isEqualToString:identifier]){
            NSLog(@"downloading is exists");
            return;
        }
    }

    
    NSArray* serviceModules = [[DataCenter defaultCenter] serviceModules];
    
    for (CubeModel* model in serviceModules){
        if ([model.identifier isEqualToString:identifier]){
            model.moduleType = CubeMoudleStatusInstalling;
            model.downloadedProcess = 0;
            model.downloadedTotalCount=100;
            [installMoudules addObject:model];
            [self saveLocalModuleList];
            CubeModuleWorkTask* async = [[CubeModuleWorkTask alloc] init];
            async.action = CubeModuleWorkTaskActionInstall;
            async.callback = self;
            async.cubeModel = model;
            [asyncs addObject:async];
            async = nil;
           
            break;
        }
    }
    
    if (!asyncIsDownloaded){
        asyncIsDownloaded = YES;
        CubeModuleWorkTask* async=[asyncs objectAtIndex:0];
        [async start];
        
        NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                            @"install",@"type",
                            async.cubeModel.identifier,@"identifier",
                            nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];
    }
    
}

-(void)updateModule:(NSString*)identifier{
    CubeModel* serviceModel=[[DataCenter defaultCenter] finidServiceCubeModule:identifier];
    if(serviceModel==nil){
        NSLog(@"update error  because  service has no model");
        return;
    }
    
    for(CubeModuleWorkTask* async in asyncs){
        if([async.cubeModel.identifier isEqualToString:identifier]){
            NSLog(@"updating  is exists");
            return;
        }
    }
    
    CubeModel* model=[[DataCenter defaultCenter] finidInstallCubeModule:identifier];
    if (model!=nil){
        model.moduleUrl=serviceModel.moduleUrl;
        model.iconUrl=serviceModel.iconUrl;
        model.build=serviceModel.build;
        model.version=serviceModel.version;
        model.name=serviceModel.name;
        model.releaseNote=serviceModel.releaseNote;
        model.platform=serviceModel.platform;

        
        model.moduleType = CubeMoudleStatusUpdating;
        model.downloadedProcess = 0;
        model.downloadedTotalCount = 100;
        [self saveLocalModuleList];
        CubeModuleWorkTask* async = [[CubeModuleWorkTask alloc] init];
        async.action = CubeModuleWorkTaskActionUpdate;
        async.callback = self;
        async.cubeModel=model;
        [asyncs addObject:async];

        if (!asyncIsDownloaded){
            asyncIsDownloaded = YES;
            async=[asyncs objectAtIndex:0];
            [async start];
            NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                                @"install",@"type",
                                async.cubeModel.identifier,@"identifier",
                                nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];
        }
    }
    else{
        NSLog(@"update error  because  install model has no model");
        return;

    }
}

-(void)uninstallModule:(NSString*)identifier{
    
    CubeModel* model=[[DataCenter defaultCenter] finidInstallCubeModule:identifier];
    if(model!=nil){
        NSString* wwwPath = [IsolatedStorageFile cubeModuleIdentifierRoot:model.identifier];
        
        [[NSFileManager defaultManager] removeItemAtPath:wwwPath error:nil];
        
        
        BOOL running=NO;
        model.moduleType = CubeMoudleStatusNone;
        for (CubeModuleWorkTask* async in asyncs){
            if ([async.cubeModel.identifier isEqualToString:model.identifier]){
                running=async.running;
                async.callback = nil;
                [async cancel];
                [asyncs removeObject:async];
                break;
            }
        }
        
        [[DataCenter defaultCenter].installMoudules removeObject:model];
        [self saveLocalModuleList];
        asyncIsDownloaded=NO;
        if(running && [asyncs count]>0){
            CubeModuleWorkTask* async=[asyncs objectAtIndex:0];
            [async start];
            asyncIsDownloaded = YES;
            NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                                @"install",@"type",
                                async.cubeModel.identifier,@"identifier",
                                nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];
        }
    }
}


#pragma mark ICubeModuleWorkTask delegate



-(void)process:(CubeModuleWorkTask*)sync{
    NSMutableArray* installMoudules = [[DataCenter defaultCenter] installMoudules];

    for (CubeModel* model in installMoudules){
        if ([model.identifier isEqualToString:sync.cubeModel.identifier]){
            model.downloadedProcess=sync.cubeModel.downloadedProcess;
            model.downloadedTotalCount = sync.cubeModel.downloadedTotalCount;
            break;
        }
    }
    
    if (sync.cubeModel.downloadedTotalCount == 0)
        return;
    
    long total = sync.cubeModel.downloadedTotalCount;
    long progress =  sync.cubeModel.downloadedProcess;
    
    
    double count = (double)(((double)progress / (double)total) * 100);
    //发送进度通知browser刷新模块进度条
    NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                        @"process",@"type",
                        sync.cubeModel.identifier,@"identifier",
                        [NSNumber numberWithInt:count],@"count",
                        nil];    
    //在模块详情页面刷新进度条
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];

}

-(void) success:(CubeModuleWorkTask*)sync{
    sync.callback = nil;
    [sync cancel];
    
    NSMutableArray* installMoudules = [[DataCenter defaultCenter] installMoudules];
    
    for (CubeModel* model in installMoudules){
        if ([model.identifier isEqualToString:sync.cubeModel.identifier]){
            if (model.moduleType == CubeMoudleStatusUpdating){
                NSArray* serviceModules=[DataCenter defaultCenter].serviceModules;
                for (CubeModel* _model in serviceModules){
                    if ([_model.identifier isEqualToString:model.identifier]){
                        model.build = _model.build;
                        model.version = _model.version;
                        break;
                    }
                }
            }
            model.moduleType = CubeMoudleStatusFinish;
            break;
        }
        }
    
    sync.cubeModel.moduleType = CubeMoudleStatusFinish;
    [self saveLocalModuleList];
    
    //管理页面中模块的增减
    NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                        @"success",@"type",
                        sync.cubeModel.identifier,@"identifier",
                        nil];

    [asyncs removeObject:sync];

    
    //刷新主页面
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];


    asyncIsDownloaded = NO;
    if ([asyncs count]>0){
        sync=[asyncs objectAtIndex:0];
        [sync start];
        asyncIsDownloaded = YES;
        
        NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                            @"install",@"type",
                            sync.cubeModel.identifier,@"identifier",
                            nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];
        
    }
}


-(void) failed:(CubeModuleWorkTask*)sync{
    sync.callback = nil;
    [sync cancel];
    
    NSMutableArray* installMoudules = [[DataCenter defaultCenter] installMoudules];
    
    for (CubeModel* model in installMoudules){
        if ([model.identifier isEqualToString:sync.cubeModel.identifier]){
            if (model.moduleType == CubeMoudleStatusUpdating){
                model.moduleType = CubeMoudleStatusFinish;
            }
            else{
                [installMoudules removeObject:model];
            }
            break;
        }
    }
    [self saveLocalModuleList];
    
    NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                        sync.cubeModel.identifier,@"identifier",
                        @"failed",@"type",
                        [NSNumber numberWithInt:101],@"count",
                        nil];

    [asyncs removeObject:sync];
        
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];



    asyncIsDownloaded = NO;
    if ([asyncs count]>0){
        sync=[asyncs objectAtIndex:0];
        [sync start];
        asyncIsDownloaded = YES;
        
        NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:
                            @"install",@"type",
                            sync.cubeModel.identifier,@"identifier",
                            nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleStatus object:dict];
    }
}


@end
